# -*- coding: utf-8 -*-
import requests
import pandas as pd
from bs4 import BeautifulSoup as bs

save_movie=[]#保存完整榜单
for page in range(10):
    url='https://maoyan.com/board/4?offset='+str(page*10)#构造url
    header = {'User-Agent': 'Chrome/92.0.4515.159 Safari/537.36'}#请求头
    #获取网页源代码
    source=requests.get(url,headers=header)
    soup=bs(source.text,'html.parser')
    #使用find-all定位获取信息
    name=soup.find_all('p',class_="name")#获取电影名字
    star=soup.find_all('p',class_="star")#获取电影主演
    rank=soup.find_all('i',class_="board-index")#获取排名
    time=soup.find_all('p',class_="releasetime")#获取上映时间
    score=soup.find_all('p',class_="score")#获取得分
    save_data=[]#保存字典
    for i,j,k,l,m in zip(name,star,rank,time,score):
        movie={}#创建字典保存数据
        movie['电影排名']=k.get_text()
        movie['电影名字']=i.get_text()
        movie['电影主演']=j.get_text().strip()[3:]#去掉两边空格并去掉“主演：”
        movie['电影上映时间']=l.get_text()[5:].strip()
        movie['电影得分']=m.get_text()
        save_data.append(movie)
        save_data1=pd.DataFrame(save_data)
    save_movie.append(save_data1)#获取10个榜单数据
    save_movie1=pd.concat(save_movie)#连接
    save_movie1.index=range(save_movie1.shape[0])#重置索引
    save_movie1.to_csv('猫眼电影Top100.csv',encoding='utf_8_sig')#保存为csv
        
